//
//  HiJonesClass.m
//  HiCar
//
//  Created by 丁一 on 2019/1/9.
//  Copyright © 2019 丁一. All rights reserved.
//

#import "HiJonesClass.h"
#import <CoreImage/CoreImage.h>
#import <CoreLocation/CLLocationManager.h>

@implementation HiJonesClass

#pragma mark - 识别人脸
+ (NSInteger)faceDetectWithImage:(UIImage *)image {
    // 图像识别能力：可以在CIDetectorAccuracyHigh(较强的处理能力)与CIDetectorAccuracyLow(较弱的处理能力)中选择，因为想让准确度高一些在这里选择CIDetectorAccuracyHigh
    NSDictionary *opts = [NSDictionary dictionaryWithObject:
                          CIDetectorAccuracyHigh forKey:CIDetectorAccuracy];
    // 将图像转换为CIImage
    CIImage *faceImage = [CIImage imageWithCGImage:image.CGImage];
    CIDetector *faceDetector=[CIDetector detectorOfType:CIDetectorTypeFace context:nil options:opts];
    // 识别出人脸数组
    NSArray *features = [faceDetector featuresInImage:faceImage];
    return features.count;
}

+(BOOL)checkName:(NSString *)_text
{
    if (_text.length<16&&_text.length>0) {
        return YES;
    }
    return NO;
}

+ (id)readLocalFileWithName:(NSString *)name {
    // 获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"json"];
    // 将文件数据化
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    // 对数据进行JSON格式化并返回字典形式
    return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

+ (NSInteger)ageWithDateOfBirth:(NSString *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *dateuser = [dateFormatter dateFromString:date];
    
    // 出生日期转换 年月日
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:dateuser];
    NSInteger brithDateYear  = [components1 year];
    NSInteger brithDateDay   = [components1 day];
    NSInteger brithDateMonth = [components1 month];
    
    // 获取系统当前 年月日
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
    NSInteger currentDateYear  = [components2 year];
    NSInteger currentDateDay   = [components2 day];
    NSInteger currentDateMonth = [components2 month];
    
    // 计算年龄
    NSInteger iAge = currentDateYear - brithDateYear - 1;
    if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) {
        iAge++;
    }
    
    return iAge;
}

+ (NSDictionary *)carinfo:(NSString *)carid{
    if (carid.length!=9) {
        return nil;
    }
    NSArray *carlist=[HiJonesClass readLocalFileWithName:@"car"];
    NSMutableDictionary *fandic = [NSMutableDictionary new];
    
    int carzid = [carid intValue];
    int carnid = carzid/1000000;
    int carpaichangid = carzid/1000;
    
    for (NSDictionary *dic in carlist) {
        int forcarnid = [[dic objectForKey:@"carnid"] intValue];
        if (forcarnid/1000000 == carnid) {
            [fandic setValue:[dic objectForKey:@"carname"] forKey:@"carname"];
            [fandic setValue:[dic objectForKey:@"carlogo"] forKey:@"carlogo"];
            
            for (int i = 0; i < [[dic objectForKey:@"carlist"] count]; i ++) {
                NSDictionary *changdic = [[dic objectForKey:@"carlist"] objectAtIndex:i];
                int changid = [[changdic objectForKey:@"cartypecomeid"] intValue];
                if (changid/1000 == carpaichangid) {
                    [fandic setValue:[changdic objectForKey:@"cartypecomename"] forKey:@"cartypecomename"];
                    
                    [[changdic objectForKey:@"cartypelist"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        NSDictionary *cardiczui = (NSDictionary *)obj;
                        if ([[cardiczui objectForKey:@"cartypeid"] intValue]==carzid) {
                            
                            if ([[cardiczui objectForKey:@"cartypename"] rangeOfString:[dic objectForKey:@"carname"]].location != NSNotFound) {
                                NSString * carstring=[cardiczui objectForKey:@"cartypename"];
                                carstring=[carstring stringByReplacingOccurrencesOfString:[dic objectForKey:@"carname"] withString:@""];
                                [fandic setValue:carstring forKey:@"cartypename"];
                            }else{
                                [fandic setValue:[cardiczui objectForKey:@"cartypename"] forKey:@"cartypename"];
                            }
                            
                            *stop = YES;
                        }
                    }];
                    
                    break;
                }
            }
            
            break;
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:fandic];
}

+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    if (data.length>20000) {
        NSData *newdata = UIImageJPEGRepresentation(image, 0.1);
        
        UIImage *resultImage = [UIImage imageWithData:newdata];
        return resultImage;
    }else{
        UIImage *resultImage = [UIImage imageWithData:data];
        return resultImage;
    }
}

#pragma mark - 图片压缩
+ (NSData *)resetSizeOfImageData:(UIImage *)sourceImage maxSize:(NSInteger)maxSize {
    
    //先判断当前质量是否满足要求，不满足再进行压缩
    __block NSData *finallImageData = UIImageJPEGRepresentation(sourceImage,1.0);
    NSUInteger sizeOrigin   = finallImageData.length;
    NSUInteger sizeOriginKB = sizeOrigin / 1000;
    
    if (sizeOriginKB <= maxSize) {
        return finallImageData;
    }
    
    //获取原图片宽高比
    CGFloat sourceImageAspectRatio = sourceImage.size.width/sourceImage.size.height;
    //先调整分辨率
    CGSize defaultSize = CGSizeMake(1024, 1024/sourceImageAspectRatio);
    UIImage *newImage = [self newSizeImage:defaultSize image:sourceImage];
    
    finallImageData = UIImageJPEGRepresentation(newImage,1.0);
    
    //保存压缩系数
    NSMutableArray *compressionQualityArr = [NSMutableArray array];
    CGFloat avg   = 1.0/250;
    CGFloat value = avg;
    for (int i = 250; i >= 1; i--) {
        value = i*avg;
        [compressionQualityArr addObject:@(value)];
    }
    
    /*
     调整大小
     说明：压缩系数数组compressionQualityArr是从大到小存储。
     */
    //思路：使用二分法搜索
    finallImageData = [self halfFuntion:compressionQualityArr image:newImage sourceData:finallImageData maxSize:maxSize];
    //如果还是未能压缩到指定大小，则进行降分辨率
    while (finallImageData.length == 0) {
        //每次降100分辨率
        CGFloat reduceWidth = 100.0;
        CGFloat reduceHeight = 100.0/sourceImageAspectRatio;
        if (defaultSize.width-reduceWidth <= 0 || defaultSize.height-reduceHeight <= 0) {
            break;
        }
        defaultSize = CGSizeMake(defaultSize.width-reduceWidth, defaultSize.height-reduceHeight);
        UIImage *image = [self newSizeImage:defaultSize
                                      image:[UIImage imageWithData:UIImageJPEGRepresentation(newImage,[[compressionQualityArr lastObject] floatValue])]];
        finallImageData = [self halfFuntion:compressionQualityArr image:image sourceData:UIImageJPEGRepresentation(image,1.0) maxSize:maxSize];
    }
    return finallImageData;
}

#pragma mark 调整图片分辨率/尺寸（等比例缩放）
+ (UIImage *)newSizeImage:(CGSize)size image:(UIImage *)sourceImage {
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
    
    CGFloat tempHeight = newSize.height / size.height;
    CGFloat tempWidth = newSize.width / size.width;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
    } else if (tempHeight > 1.0 && tempWidth < tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
    }
    
    UIGraphicsBeginImageContext(newSize);
    [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
#pragma mark 二分法
+ (NSData *)halfFuntion:(NSArray *)arr image:(UIImage *)image sourceData:(NSData *)finallImageData maxSize:(NSInteger)maxSize {
    NSData *tempData = [NSData data];
    NSUInteger start = 0;
    NSUInteger end = arr.count - 1;
    NSUInteger index = 0;
    
    NSUInteger difference = NSIntegerMax;
    while(start <= end) {
        index = start + (end - start)/2;
        
        finallImageData = UIImageJPEGRepresentation(image,[arr[index] floatValue]);
        
        NSUInteger sizeOrigin = finallImageData.length;
        NSUInteger sizeOriginKB = sizeOrigin / 1024;
        NSLog(@"当前降到的质量：%ld", (unsigned long)sizeOriginKB);
        NSLog(@"\nstart：%zd\nend：%zd\nindex：%zd\n压缩系数：%lf", start, end, (unsigned long)index, [arr[index] floatValue]);
        
        if (sizeOriginKB > maxSize) {
            start = index + 1;
        } else if (sizeOriginKB < maxSize) {
            if (maxSize-sizeOriginKB < difference) {
                difference = maxSize-sizeOriginKB;
                tempData = finallImageData;
            }
            if (index<=0) {
                break;
            }
            end = index - 1;
        } else {
            break;
        }
    }
    return tempData;
}

+ (NSString *)height:(NSString *)height weight:(NSString *)weight{
    if (height&&weight&&![height isEqualToString:@""]&&![weight isEqualToString:@""]) {
        CGFloat heightint = [height floatValue]/100;
        CGFloat weightint = [weight floatValue];
        
        CGFloat bmizhi = weightint/(heightint*heightint);
        
        if (bmizhi<=18.5) {
            return @"骨干身材";
        }else if (bmizhi>18.5&&bmizhi<=25){
            return @"苗条身材";
        }else if (bmizhi>25&&bmizhi<=29){
            return @"微胖身材";
        }else{
            return @"丰满身材";
        }
        
    }else{
        if (height&&![height isEqualToString:@""]) {
            return [NSString stringWithFormat:@"%@cm",height];
        }else if (weight&&![weight isEqualToString:@""]){
            return [NSString stringWithFormat:@"%@kg",weight];
        }else{
            return nil;
        }
    }
}

+ (CGFloat)getContent:(NSString *)content width:(CGFloat)width font:(UIFont *)font jianju:(CGFloat)jianju{
    NSMutableAttributedString *attributedStringT = [[NSMutableAttributedString alloc] initWithString:content];
    NSMutableParagraphStyle *paragraphStyleT = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyleT setLineSpacing:jianju];
    [attributedStringT addAttribute:NSParagraphStyleAttributeName value:paragraphStyleT range:NSMakeRange(0, [content length])];
    
    [attributedStringT addAttribute:NSFontAttributeName
                              value:font
                              range:NSMakeRange(0, attributedStringT.length)];
    
    CGRect rect = [attributedStringT boundingRectWithSize:CGSizeMake(width, 100000)
                                                  options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                  context:nil];
    return rect.size.height;
}


+(CLLocationDistance)Juli:(NSString *)lat anglong:(NSString *)longitude{
    CLLocation *orig=[[CLLocation alloc] initWithLatitude:[[DEFAULTS objectForKey:City_WeiDu_Key] doubleValue]  longitude:[[DEFAULTS objectForKey:City_JinDu_Key] doubleValue]];
    CLLocation* dist=[[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[longitude doubleValue]];
    
    CLLocationDistance kilometers=[orig distanceFromLocation:dist]/1000;
    
    return kilometers;
}

/**
 *  显示几分钟前、几小时前等 str格式：yyyy-MM-dd HH:mm:ss
 */
+ (NSString *)compareCurrentTime:(NSString *)str{
    
    NSDateFormatter *yourformatter = [[NSDateFormatter alloc] init];
    
    [yourformatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate * d = [yourformatter dateFromString:str];
    
    NSTimeInterval late = [d timeIntervalSince1970]*1;
    
    NSString * timeString = nil;
    
    NSDate * dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval now = [dat timeIntervalSince1970]*1;
    
    NSTimeInterval cha = late - now;
    
    if (cha<5) {
        timeString = [NSString stringWithFormat:@"已结束"];
        return timeString;
    }
    
    if (cha/3600 < 1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        int num= [timeString intValue];
        
        if (num <= 1) {
            
            timeString = [NSString stringWithFormat:@"马上开始"];
            
        }else{
            
            timeString = [NSString stringWithFormat:@"马上开始"];
            
        }
        
    }
    
    if (cha/3600 > 1 && cha/86400 < 1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        timeString = [NSString stringWithFormat:@"%@小时后", timeString];
        
    }
    
    if (cha/86400 > 1)
        
    {
        
        int num = cha/86400;
        
        if (num < 2) {
            
            NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
            [outputFormatter setLocale:[NSLocale currentLocale]];
            [outputFormatter setDateFormat:@"HH:mm"];
            NSString *str = [outputFormatter stringFromDate:d];
            
            timeString = [NSString stringWithFormat:@"明天%@",str];
            
        }else if(num == 2){
            
            NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
            [outputFormatter setLocale:[NSLocale currentLocale]];
            [outputFormatter setDateFormat:@"HH:mm"];
            NSString *str = [outputFormatter stringFromDate:d];
            
            timeString = [NSString stringWithFormat:@"后天%@",str];
            
        }else{
            NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
            [outputFormatter setLocale:[NSLocale currentLocale]];
            [outputFormatter setDateFormat:@"MM月dd日HH:mm"];
            NSString *str = [outputFormatter stringFromDate:d];
            timeString = str;
        }
    }
    return timeString;
}

+ (NSString *) timeZhuan:(NSString *)time
{
    NSDateFormatter *yourformatter = [[NSDateFormatter alloc] init];
    
    [yourformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate * d = [yourformatter dateFromString:time];
    
    NSTimeInterval late = [d timeIntervalSince1970]*1;
    
    NSString * timeString = nil;
    
    NSDate * dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval now = [dat timeIntervalSince1970]*1;
    
    NSTimeInterval cha = now - late;
    if (cha/3600 < 1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        int num= [timeString intValue];
        
        if (num <= 1) {
            
            timeString = [NSString stringWithFormat:@"刚刚"];
            
        }else{
            
            timeString = [NSString stringWithFormat:@"%@分钟前", timeString];
            
        }
        
    }
    
    if (cha/3600 > 1 && cha/86400 < 1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        timeString = [NSString stringWithFormat:@"%@小时前", timeString];
        
    }
    
    if (cha/86400 > 1)
        
    {
        int num = cha/86400;
        
        if (num < 2) {
            
            timeString = [NSString stringWithFormat:@"昨天"];
            
        }else if(num == 2){
            
            timeString = [NSString stringWithFormat:@"前天"];
            
        }else if (num > 2 && num <7){
            
            timeString = [NSString stringWithFormat:@"%i天前", num];
            
        }else if (num >= 7 && num <= 10) {
            
            timeString = [NSString stringWithFormat:@"1周前"];
            
        }else if(num > 10){
            NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
            [outputFormatter setLocale:[NSLocale currentLocale]];
            [outputFormatter setDateFormat:@"MM月dd"];
            NSString *str = [outputFormatter stringFromDate:d];
            timeString = str;
        }
    }
    return timeString;
}

+ (BOOL)isUserNotificationEnable { // 判断用户是否允许接收通知
    BOOL isEnable = NO;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0f) { // iOS版本 >=8.0 处理逻辑
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    } else { // iOS版本 <8.0 处理逻辑
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        isEnable = (UIRemoteNotificationTypeNone == type) ? NO : YES;
    }
    return isEnable;
}

+ (BOOL)laction_open{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized)) {
        
        //定位功能可用
        return YES;
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        
        //定位不能用
        return NO;
    }
    return NO;
}


/** 分享 */
+ (void)mq_share:(NSArray *)items target:(id)target success:(SucceessBlock)successBlock {
    if (items.count == 0 || target == nil) {
        return;
    }
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    if (@available(iOS 11.0, *)) {//UIActivityTypeMarkupAsPDF是在iOS 11.0 之后才有的
        activityVC.excludedActivityTypes = @[UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypeOpenInIBooks,UIActivityTypeMarkupAsPDF];
    } else if (@available(iOS 9.0, *)) {//UIActivityTypeOpenInIBooks是在iOS 9.0 之后才有的
        activityVC.excludedActivityTypes = @[UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypeOpenInIBooks];
    }else {
        activityVC.excludedActivityTypes = @[UIActivityTypeMessage,UIActivityTypeMail];
    }
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            if (successBlock) {
                successBlock(YES, @"");
            }
        }else {
            if (successBlock) {
                successBlock(NO, @"");
            }
        }
    };
    //这儿一定要做iPhone与iPad的判断，因为这儿只有iPhone可以present，iPad需pop，所以这儿actVC.popoverPresentationController.sourceView = self.view;在iPad下必须有，不然iPad会crash，self.view你可以换成任何view，你可以理解为弹出的窗需要找个依托。
    UIViewController *vc = target;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        activityVC.popoverPresentationController.sourceView = vc.view;
        [vc presentViewController:activityVC animated:YES completion:nil];
    } else {
        [vc presentViewController:activityVC animated:YES completion:nil];
    }
}

@end
